<?php

namespace Yi\Wechat\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Illuminate\Support\Facades\Log;
use Auth;


class MiniprogramAppAuth extends BaseMiddleware
{

    protected $auth;

    function __construct()
    {
        $this->auth = Auth::guard('miniprogram');
    }

    /**
     * JWT 检测当前登录的平台
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  null $role
     * @return mixed
     */
    public function handle($request, Closure $next, $role = null)
    {
        try {
            $tokenRole = $this->auth->parseToken()->getClaim('role');
            $role = 'miniprogram';
            if ($tokenRole != $role) {
                $data['message'] = '角色验证错误';
                $data['code'] = 10001;
                $data['tokenRole'] = $tokenRole;
                return response()->json($data, 401);
            }


            // token 认证
            $token = str_replace('Bearer ', '', ($request->header('Authorization')));
            $unique_str = uniqid() . "_" . time();
            Log::debug('auth-data', [
                'unique_flag' => $unique_str,
                'requst_url' => $request->url(),
                'Authorization_token' => $token
            ]);

            $user = $this->auth->user(); #当前用户
            Log::debug("auth-user", [$user]);

            $auth =  $this->auth->authenticate();
            Log::debug("auth-auth", [$auth]);

            if ($auth && $user) {

                $user_id = $this->auth->user()->id;

                Log::debug('auth-data', [
                    'unique_str' => $unique_str,
                    'user_id' => $user_id,
                ]);

                //传值至控制器
                $request->setUserResolver(function () use ($user) {
                    return $user;
                });
                return $next($request);
            } else {
                $data['message'] = '请重新登录';
                $data['auth'] = $auth;
                return response()->json($data, 401);
            }
        } catch (JWTException $e) {
            $data['message'] = '认证失败';
            $data['code'] = 1001;
            return response()->json($data, 401);
        }
    }
}
